package com.google.code.mergeinformer.util.synchronization;

/**
 * @author Dmitry Golubev
 */
class ExtrusiveMutex<K, O> extends Mutex<K, O> {

    private final MutexProvider<K, O> mutexProvider;
    private final long producerThreadId;

    @SafeVarargs
    ExtrusiveMutex(MutexProvider<K, O> mutexProvider, K key, O... operations) {
        super(key, operations);
        this.mutexProvider = mutexProvider;
        this.producerThreadId = Thread.currentThread().getId();
    }

    synchronized void executeExtrusiveBlock(MutexProvider.ExtrusiveBlock extrusiveBlock) {
        if (Thread.currentThread().getId() != producerThreadId) {
            return;
        }
        try {
            extrusiveBlock.execute();
        } finally {
            mutexProvider.discardMutex(this);
        }
    }
}
